package com.javabasic.compare;

import lombok.Data;

import java.util.Comparator;
import java.util.TreeSet;

public class TreeSetCompareTest {

    public static void main(String[] args) {

        // 自然排序 Student必须实现Comparable接口，否则会抛出ClassCastException
        TreeSet<Student> treeSet = new TreeSet<>();

        Student stu1 = new Student(1, "Little");

        Student stu2 = new Student(2, "Cyntin");

        Student stu3 = new Student(3, "Tony");

        Student stu4 = new Student(4, "Gemini");

        treeSet.add(stu2);
        treeSet.add(stu3);
        treeSet.add(stu4);
        treeSet.add(stu1);

        // sort with implements Comparable
        System.out.println(treeSet.toString());

        // sort with Comparator  比较器排序
        TreeSet<Student> treeSet1 = new TreeSet<>(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });

        treeSet1.add(stu2);
        treeSet1.add(stu3);
        treeSet1.add(stu4);
        treeSet1.add(stu1);

        System.out.println(treeSet1.toString());

    }
}
